import styled, { css } from 'styled-components'
import { useEffect, useMemo, useState, useCallback, useRef } from 'react'
import BScroll from '@better-scroll/core'
import Pullup from '@better-scroll/pull-up'
import { TeamDetailResponse, TeamLevel } from '../../service/interface'
import { useSelector } from 'react-redux'
import { RootState } from '../../store'
import Empty from '../../component/Empty'
import { useTranslation } from 'react-i18next'
// import InfiniteScroll from 'react-infinite-scroll-component';
import Icon from '../../component/Icon'
import Space from '../../component/Space'
import IconAvatar from '../../asserts/avatar_default.png'
import IconTeamEmpty from '../../asserts/tab_team_normal.png'
import { teamDetail } from '../../service'
import { formatBase64Image } from '../../utils/common'
import Telegram from '../../utils/telegram'
import Message from '../../component/Message'
import gtag from '../../google/analytics'
import { GtagEvent } from '../../google/analytics/Event'

BScroll.use(Pullup)


const ContentBox = styled.div`
    width: 100%;
    flex: 1;
    overflow-y: auto;
    margin-bottom: 1.25rem;
`

const Container = styled.div`
`
const Item = styled.li`
    width: 100%;
    display: flex;
    padding: 1rem;
    box-sizing: border-box;
    align-items: center;
`
const ItemLeft = styled.img`
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 50%;
`

const Nickname = styled.span`
    overflow: hidden; 
    text-overflow: ellipsis;
    white-space:nowrap;
`

const ItemCenter = styled.div`
    flex: 1;
    padding: 0 .625rem;
    display: flex;
    flex-direction: column;
    align-items: start;
    overflow: hidden;
`

const ItemCenterTop = styled.div`
    font-weight: bold;
    font-size: .875rem;
    color: ${(prop) => prop.theme.text.normal};
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
`

const ItemCenterBottom = styled.div`
    width: 100%;
    font-size: .875rem;
    margin-top: .4375rem;
    color: ${(prop) => prop.theme.text.coin};
    display: flex;
    align-items: center;
    .cash {
        margin-left: .1875rem;
    }
`

const InviteCount = styled.div`
    color: ${(prop) => prop.theme.text.coin};
    font-size: .625rem;
    font-weight: bold;
`

const StopStatus = css`
    background-color: ${(prop) => prop.theme.background.stop};
    color: ${(prop) => prop.theme.text.stop};
`

const WorkingStatus = css`
    background-color: ${(prop) => prop.theme.background.working};
    color: ${(prop) => prop.theme.text.working};
`

const ItemRight = styled.div<{ $isWorking: number }>`
    width: 3.125rem;
    min-width: 3.125rem;
    height: 1.5rem;
    ${({ $isWorking }) => $isWorking ? WorkingStatus : StopStatus};
    border-radius: .5rem;
    font-size: .625rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
`

const StatusItem = ItemRight;

const IconArrow = styled(Icon)`
    margin-left: 1rem;
`

interface Props {
    level: TeamLevel
    className?: string;
}

const START_PAGE = 1

const List: React.FC<Props> = ({ level, className }) => {

    const { t } = useTranslation()
    const user = useSelector((state: RootState) => state.user)
    const ref = useRef<HTMLDivElement>(null)
    const pageRef = useRef<number>(START_PAGE)
    const hasMoreRef = useRef<boolean>(false)
    const [list, setList] = useState<TeamDetailResponse[]>([])

    const empty = useMemo(() => !list.length, [list])

    const fetchMoreData = useCallback(async (page: number, level: TeamLevel) => {
        const result = await teamDetail({
            pageNum: String(page),
            pageSize: String(20),
            genType: level
        })

        // const item = () => ({
        //     detState: 10,
        //     image: '',
        //     inviteNum: 1,
        //     nikeName: String(news Date().getTime()),
        //     userId: String(new Date().getTime()),
        //     parent1Name: level,
        //     rewardAmt: '1231',
        //     username: String(new Date().getTime()),
        // })

        // teamDetail
        // const result = {
        //     success: true,
        //     data: {
        //         list: new Array(10).fill(item())
        //     },
        // }

        if (!result.success) {
            hasMoreRef.current = false
            return
        }

        const more = Boolean(result.data?.list?.length);
        if (more) {
            // update current page
            pageRef.current = page;
        }

        hasMoreRef.current = more
        if (page === START_PAGE) {
            setList(result.data?.list || [])
        } else {
            setList(pre => pre.concat(result.data?.list || []))
        }
    }, [])

    useEffect(() => {
        if (!ref.current) {
            return
        }

        const dom = ref.current;
        const bs = new BScroll(dom, { bounce: true, click: true, pullUpLoad: true, stopPropagation: true });
        bs.enable();
        bs.openPullUp({
            threshold: 5
        })
        bs.on('pullingUp', async () => {
            if (hasMoreRef.current === false) {
                bs.finishPullUp();
                return
            }
            await fetchMoreData(pageRef.current + 1, level)
            bs.finishPullUp();
            bs.refresh();
        })

        return () => {
            bs.destroy()
        }

    }, [fetchMoreData, level, empty])

    useEffect(() => {
        pageRef.current = START_PAGE
        hasMoreRef.current = false
        setList([])
        fetchMoreData(START_PAGE, level)
    }, [level, user, fetchMoreData])

    const onItemClick = (item: TeamDetailResponse) => {
        const username = item.userName
        if (!username) {
            Message.error(t('error.noUsername'))
            return
        }

        gtag.event(GtagEvent.Chat, { level })
        Telegram.chat(username)
    }

    return <ContentBox
        className={className}
        ref={ref}
    >
        {empty ? <Empty
            icon={IconTeamEmpty}
            subTitle={t('empty.popularize')}
            style={{ marginTop: '0', paddingBottom: '0' }}
        /> :
            <Container>
                {list.map((item, idx) =>
                    <Item
                        key={item.nikeName + idx}
                        onClick={() => onItemClick(item)}
                    >
                        <ItemLeft src={formatBase64Image(item.image) || IconAvatar} />
                        <ItemCenter>
                            <ItemCenterTop>
                                <Nickname>{item.nikeName}</Nickname>
                                <Space minWidth='8px' />
                                <StatusItem $isWorking={item.detState === 1 ? 1 : 0}>{item.detState === 1 ? <span>{t('team.mining')}</span> : t('team.stop')}</StatusItem>
                            </ItemCenterTop>
                            <ItemCenterBottom>
                                <Icon
                                    name='icon_coin'
                                    width='.75rem'
                                />
                                <span className='cash'>{`+${item.rewardAmt}`}</span>
                                <Space maxWidth='1.1875rem' />
                                <Icon
                                    name='ton_coin'
                                    width='.75rem'
                                />
                                <span className='cash'>{`+${item.rewardAmtTon || '0.00'}`}</span>
                                <Space minHeight='100%' />
                                <InviteCount>{t('team.fission_num', { num: item.inviteNum })}</InviteCount>
                                {/* <Space minHeight='100%' /> */}
                            </ItemCenterBottom>
                        </ItemCenter>
                        {/* <ItemRight $isWorking={item.detState === 1 ? 1 : 0}>{item.detState === 1 ? <span>{t('team.mining')}</span> : t('team.stop')}</ItemRight> */}
                        <IconArrow
                            name={item.userName ? 'arrow_right' : ''}
                            width='.75rem'
                        />
                    </Item>
                )}
            </Container>}
    </ContentBox>


}

export default List
